/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.sec.content.role;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.EntityConstants;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.PrivilegChecker;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.Resource;
import han.bifang.gwt.client.common.entity.Role;
import han.bifang.gwt.client.common.entity.User;
import han.bifang.gwt.client.common.entity.Usergroup;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.sec.CustomCheckBox;
import han.bifang.gwt.client.sec.SecurityMessages;

import java.util.ArrayList;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class RoleResourceContent extends Content implements
		GroupAndResourceSearcher {

	private SecurityMessages cons = null;

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;
	private VerticalPanel panel;

	private String roleId;

	private SimplePanel tablePanel;
	private CustomCheckBox[] checks;
	// private ArrayList<User> g, tmp;

	private int size = 10;

	private int currentPage = 1;

	private boolean loaded;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			// for (CustomCheckBox check : checks) {
			// if (check.isChecked()) {
			// User gr = (User) check.getProperties();
			// g.remove(gr);
			// }
			// }
			searchResource(currentPage, size);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			// g.addAll(tmp);
			// tmp = null;
			searchResource(currentPage, size);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb2 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			// Window.alert("ok");
			ArrayList ret = (ArrayList) res.getResponse();
			int total = (Integer) ret.get(0);
			// Window.alert("total " + total);
			ArrayList list = (ArrayList) ret.get(1);

			Grid table = new Grid(list.size() + 1, 5);
			table.setWidth("60%");
			table.setCellPadding(1);
			table.setCellSpacing(1);
			table.setBorderWidth(1);

			ColumnFormatter cf = table.getColumnFormatter();

			cf.setWidth(0, "10%");
			cf.setWidth(1, "20%");
			cf.setWidth(2, "20%");
			cf.setWidth(3, "20%");
			cf.setWidth(4, "20%");

			CellFormatter ff = table.getCellFormatter();
			ff.setStyleName(0, 0, "tablecol");
			ff.setStyleName(0, 1, "tablecol");
			ff.setStyleName(0, 2, "tablecol");
			ff.setStyleName(0, 3, "tablecol");
			ff.setStyleName(0, 4, "tablecol");

			table.setHTML(0, 0, "&nbsp");
			table.setHTML(0, 1, cons.serviceName());
			table.setHTML(0, 2, cons.localServiceCode());
			table.setHTML(0, 3, cons.remoteServiceCode());

			table.setHTML(0, 4, cons.serviceType());
			VerticalPanel v = new VerticalPanel();
			v.setWidth("100%");
			v.add(table);
			if (total != 0) {

				v.setWidth("100%");
				v.setSpacing(5);

				checks = new CustomCheckBox[list.size()];
				for (int i = 1, j = list.size() + 1; i < j; i++) {
					Resource s = (Resource) list.get(i - 1);
					checks[i - 1] = new CustomCheckBox();
					checks[i - 1].setProperties(s);
					table.setWidget(i, 0, checks[i - 1]);
					table.setHTML(i, 1, s.getProperty1());

					table.setHTML(i, 2, s.getProperty2());
					table.setHTML(i, 3,
							StringUtils.isEmpty(s.getProperty3()) ? "&nbsp;"
									: s.getProperty3());
					if (s.getType().equals(
							EntityConstants.RESOURCE_LOCAL_SERVICE)) {
						table.setHTML(i, 4, cons.localService());
					} else {
						table.setHTML(i, 4, cons.mappingService());
					}

				}
				// v.add(table);
				v.add(new HTML("&nbsp;"));
				HorizontalPanel h = new HorizontalPanel();
				h.setWidth("60%");
				h.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				h.add(new HTML(cons.page(total, currentPage)));
				v.add(h);
				if (total > 1) {

					if (currentPage > 1) {
						Button pre = new Button(cons.previous());
						pre.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage--;
								searchResource(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(pre);
					}
					if (currentPage < total) {
						Button n = new Button(cons.next());
						n.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage++;
								searchResource(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(n);

					}

				}

			}
			tablePanel.setWidget(v);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public RoleResourceContent(SecurityMessages cons,
			BifangGWTServiceAsync service, GwtContext context, String id) {
		this.service = service;
		this.context = context;
		this.cons = cons;
		this.roleId = id;

		panel = new VerticalPanel();
		panel.setSpacing(5);
		panel.setWidth("100%");

		tablePanel = new SimplePanel();
		tablePanel.setWidth("100%");
		panel.add(tablePanel);

		initWidget(panel);

	}

	public void onLoad() {
		if (!loaded) {
			searchResource(currentPage, size);

			HorizontalPanel h = new HorizontalPanel();
			Button b = new Button(cons.addResource(), new ClickListener() {
				public void onClick(Widget sender) {
					DialogBox dialogBox = createDialogBox();
					dialogBox.setText(cons.addResource());
					dialogBox.center();
					dialogBox.show();
				}
			});

			Button b1 = new Button(cons.removeResource());
			b1.addClickListener(new ClickListener() {

				public void onClick(Widget sender) {
					RequestObject req = new RequestObject();
					req
							.setAction("han.bifang.gwt.server.action.sec.role.RemoveResourcesOfRoleAction");
					ArrayList<String> param = new ArrayList<String>();
					param.add(roleId);

					for (CustomCheckBox check : checks) {
						if (check.isChecked()) {
							Resource gr = (Resource) check.getProperties();
							param.add(gr.getId());
						}
					}

					req.setRequest(param);
					service.call(req, cb);

				}

			});

			h.add(b);
			h.add(new HTML("&nbsp;&nbsp;"));
			h.add(b1);

			panel.add(new HTML("&nbsp;"));
			if (PrivilegChecker.hasPrivilege(context, null))
				panel.add(h);
			loaded = true;
		}

	}

	// private void refreshTable(List<User> g) {
	// FlexTable table = new FlexTable();
	// table.setWidth("60%");
	// table.setCellPadding(1);
	// table.setCellSpacing(1);
	// table.setBorderWidth(1);
	//
	// ColumnFormatter cf = table.getColumnFormatter();
	// cf.setWidth(0, "10%");
	// cf.setWidth(1, "20%");
	// cf.setWidth(1, "20%");
	// cf.setWidth(2, "50%");
	//
	// CellFormatter ff = table.getCellFormatter();
	// ff.setStyleName(0, 0, "tablecol");
	// ff.setStyleName(0, 1, "tablecol");
	// ff.setStyleName(0, 2, "tablecol");
	// ff.setStyleName(0, 3, "tablecol");
	//
	// table.setHTML(0, 0, "&nbsp;");
	// table.setHTML(0, 1, cons.userName());
	// table.setHTML(0, 2, cons.loginName());
	// table.setHTML(0, 3, cons.description());
	//
	// checks = new CustomCheckBox[g.size()];
	// for (int i = 0, j = g.size(); i < j; i++) {
	// int row = table.getRowCount();
	// table.insertRow(row);
	// checks[i] = new CustomCheckBox();
	// checks[i].setProperties(g.get(i));
	//
	// table.setHTML(row, 0, g.get(i).getUserName());
	// table.setHTML(row, 1, g.get(i).getLoginName());
	// table.setHTML(row, 2, g.get(i).getDescription());
	//
	// }
	// tablePanel.setWidget(table);
	// }

	private DialogBox createDialogBox() {
		DialogBox dialogBox = new DialogBox();
		SearchResourcePanel gp = new SearchResourcePanel(cons, service,
				dialogBox, roleId);
		gp.setSearcher(this);
		dialogBox.setWidget(gp);

		return dialogBox;
	}

	public void onRoleSearchResult(ArrayList<Role> u) {
		// TODO Auto-generated method stub

	}

	public void onUserSearchResult(ArrayList<User> u) {

	}

	private void searchResource(int page, int size) {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.sec.role.GetResourcesOfRoleAction");
		ArrayList p = new ArrayList();

		p.add(roleId);
		p.add(page);
		p.add(size);
		req.setRequest(p);
		service.call(req, cb2);
	}

	public void onGroupResult(ArrayList<Usergroup> g) {
		// TODO Auto-generated method stub

	}

	public void onResourceResult(ArrayList<Resource> r) {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.sec.role.AddResourcesOfRoleAction");
		ArrayList<String> param = new ArrayList<String>();
		param.add(roleId);

		for (Resource gg : r) {
			param.add(gg.getId());
		}

		req.setRequest(param);
		service.call(req, cb1);

	}
}
